<template>
  <main-nav-bar>
    <template v-slot:home-nav-back>
      <div><i class="iconfont icon-jiantou2"></i></div>
    </template>
  </main-nav-bar>
  <div class="textContainer">
    <textarea
      name=""
      id=""
      v-model="textContent"
      cols="5"
      rows="10"
      placeholder="写点什么..."
    ></textarea>
    <div class="imgContainer">
      <div v-for="(item, index) in fileList.img" :key="item" class="IMG">
        <img :src="item.url" alt="" />
        <i class="iconfont icon-shanchu" @click="deleteImg(index)"></i>
      </div>
      <div class="add-image" @click="addImage" v-if="canAdd">
        +
        <input
          type="file"
          ref="selectImage"
          accept="image/gif,image/jpeg,image/jpg,image/png"
          @change="imageChange"
        />
      </div>
    </div>
    <!-- <van-uploader
    v-model="fileList.img"
    multiple
    :preview-full-image="false"
    :after-read="afterRead"
  /> -->
    <div class="publish" :class="{ 'no-click': noClick }" @click="send">
      发布
    </div>
  </div>

  <van-loading type="spinner" v-if="isLoading">上传中...</van-loading>
</template>

<script>
import { onUpdated, ref, reactive, toRef, onMounted } from "vue";
import { useRouter } from "vue-router";
import MainNavBar from "../../components/content/mainnavbar/MainNavBar.vue";
import { request } from "/@/network/request.js";
import { Toast } from "vant";
export default {
  components: {
    MainNavBar,
  },
  setup() {
    const router = useRouter();
    let canAdd = ref(true);
    let selectImage = ref(null);
    let textContent = ref("");
    const isLoading = ref(false)
    const fileList = reactive({
      img: [],
    });
    const noClick = ref(false);
    const formData = ref([]);
    const addImage = () => {
      selectImage.value.value = null;
      selectImage.value.click();

      // console.log(selectImage.files[0]);
    };
    const imageChange = () => {
      const imgName = String(selectImage.value.files[0].name)
      const type = imgName.slice(imgName.lastIndexOf(".")+1).toLocaleLowerCase()
      const rules = /png|jpg|jpeg|gif/
      if(!rules.test(type)){
        Toast("图片格式错误");
        return
      }
      fileList.img.push({
        url: URL.createObjectURL(selectImage.value.files[0]),
      });
      formData.value.push(selectImage.value.files[0]);
      //   最多上传三张图
      if (fileList.img.length === 3) {
        canAdd.value = false;
      }
    };
    const deleteImg = (index) => {
      fileList.img.splice(index, 1);
      formData.value.splice(index, 1);
      if (fileList.img.length < 3) {
        canAdd.value = true;
      }
    };
    const send = async () => {
      if (formData.value.length == 0 && textContent.value == "") {
        Toast("请写点什么...");
        return;
      }
      isLoading.value = true;
      noClick.value = true;
      let file = new FormData();
      file.append("token", 1);
      file.append("user_id", sessionStorage.getItem("user_id"));
      file.append("intro", textContent.value);
      formData.value.forEach((item) => {
        file.append("file[]", item);
      });
      try {
        const result = await request({
          url: "v1.club/add",
          data: file,
        });
        if (result.code == 200) {
          isLoading.value = false;
          Toast({
            mask: true,
            message: result.msg,
            // message: "成功",
            duration: 1500,
          });
          let timer = setInterval(() => {
            noClick.value = false;
            router.push("/community");
            clearInterval(timer);
          }, 1550);
        } else {
          isLoading.value = false;
          noClick.value = false;
          Toast({
            message: result.msg,
            // message: "失败",
          });
        }
      } catch (error) {
        isLoading.value = false;
        noClick.value = false;
        Toast({
          mask: true,
          message: "发布失败 请重新发布",
          duration: 1500,
        });
        
      }
    };
    onMounted(() => {
      // let url = encodeURI("http://photobook.zhongaotech.com")
      //  window.location.href =
      // "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxb4cd52cc33df2328&redirect_uri=" +
      // url +
      // "&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
    });
    return {
      addImage,
      fileList,
      selectImage,
      canAdd,
      imageChange,
      textContent,
      send,
      deleteImg,
      noClick,
      isLoading
    };
  },
};
</script>

<style scoped>
.publish.no-click {
  pointer-events: none;
  background-color: #ccc;
}
.textContainer {
  width: 88.267vw;
  margin: 0 auto;
  padding-bottom: 26.667vw;
}
.textContainer textarea {
  width: 100%;
  outline: none;
  border: none;
  margin-top: 19.733vw;
  resize: none;
}
.textContainer textarea::placeholder {
  color: #7a7a7a;
}
.imgContainer .IMG {
  margin-bottom: 10px;
  position: relative;
}
.imgContainer i {
  position: absolute;
  right: 2.667vw;
  top: 1.333vw;
  font-size: 5.333vw;
  color: #fff;
}

.imgContainer img {
  width: 28.267vw;
  height: 28.267vw;
  margin-right: 1.067vw;
  vertical-align: middle;
}
.imgContainer .add-image {
  font-size: 40px;
  color: #ccc;
  width: 28.267vw;
  line-height: 28.267vw;
  text-align: center;
  height: 28.267vw;
  border: 1px dashed #ccc;
}
.imgContainer input {
  display: none;
}
.imgContainer {
  display: flex;
  flex-wrap: wrap;
}
.publish {
  position: fixed;
  bottom: 5.333vw;
  width: 89.067vw;
  height: 13.333vw;
  background-color: #6e0802;
  font-size: 4.8vw;
  color: #fff;
  text-align: center;
  line-height: 13.333vw;
  border-radius: 2.667vw;
}
/* .loading{
  width: 100vw;
  height: 100vh;
  position: fixed;
  background-color: #fff;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999999999;
  transform: translateZ(2px);
} */
</style>